package cn.uncode.dal.asyn;

import java.util.concurrent.Callable;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.uncode.dal.core.BaseDAL;
import cn.uncode.dal.criteria.QueryCriteria;
import cn.uncode.dal.datasource.DBContextHolder;
import cn.uncode.dal.descriptor.QueryResult;



/**
 * 分布异步任务
 * 
 * @author juny.ye
 */
public class ShardsQueryCallable implements Callable<QueryResult> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShardsQueryCallable.class);
    
    private final BaseDAL baseDAL;
    
    private final AsynContext context;
    
    public ShardsQueryCallable(BaseDAL baseDAL, AsynContext context){
    	this.baseDAL = baseDAL;
    	this.context = context;
    }
    
	@Override
	public QueryResult call() throws Exception {
		if(context.getObj() != null){
			if(StringUtils.isNotBlank(context.getDatabase())){
				DBContextHolder.swithTo(context.getDatabase());
			}
			if(context.getMethod().equals(Method.SELECT_BY_CRITERIA)){
				QueryCriteria shardQueryCriteria = (QueryCriteria) context.getObj();
		    	shardQueryCriteria.setTable(context.getTable());
				shardQueryCriteria.setPageIndex(0);
				shardQueryCriteria.setPageSize(0);
				shardQueryCriteria.setRecordIndex(0);
				shardQueryCriteria.setLimit(0);
		    	QueryResult queryResult = baseDAL.selectByCriteria(context.getFields(), shardQueryCriteria);
		    	return queryResult;
			}else if(context.getMethod().equals(Method.SELECT_BY_IDS)){
				QueryResult queryResult = baseDAL.selectByIds(context.getFields(), context.getTable(), context.getObj());
				return queryResult;
			}
		}
		return null;
	}
    
   

}
